package com.qianxx.component.activity.recycleview.quick_return;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.qianxx.component.R;

import java.util.List;


public class QuickReturnAdapter extends RecyclerView.Adapter<QuickReturnAdapter.ViewHolder> {
    OnItemClickListener listener;
    View mView;
    final int TYPE_HEADER = 0;
    final int TYPE_CHILD = 1;
    Context context;
    List<String> list;

    public QuickReturnAdapter(Context context,List<String> list){
        this.context = context;
        this.list = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
        if (mView != null && viewType == TYPE_HEADER) {
            return new ViewHolder(mView, null);
        }
        View v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.indexable_list_item, parent, false);
        ViewHolder holder = new ViewHolder(v, listener);
        holder.text = (TextView) v.findViewById(R.id.text);
        return holder;
    }

    @Override
    public void onBindViewHolder(QuickReturnAdapter.ViewHolder holder,
                                 int position) {
        // 如果当前列表项是首项,则不添加任何元素
        if (holder.getItemViewType() == TYPE_HEADER)
            return;
        // 如果当前列表项不是是首项,则设置内容
        if (mView != null) {
            position = position - 1;
        }
        holder.text.setText(list.get(position));
    }

    @Override
    public int getItemCount() {
        return mView != null ? list.size() + 1 : list.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? TYPE_HEADER : TYPE_CHILD;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements
            View.OnClickListener {
        private TextView text;
        private OnItemClickListener listener;

        public ViewHolder(View view, OnItemClickListener listener) {
            super(view);
            this.listener = listener;
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.onItemClick(v, getPosition());
            }
        }
    }

    public void addHeaderView(View view) {
        this.mView = view;
    }

    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }
}
